package Com.Ring.TradingMobile;

import java.util.ArrayList;

import Com.Ring.TradingMobile.Lib.*;
import Com.Ring.TradingMobile.Service.WebService;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.TableRow.LayoutParams;

public class TrangThaiLenhActivity extends Activity {
	private int[] StrHeaderId = new int[] { R.string.strMaCK,
			R.string.strSide, R.string.strOrderVol,
			R.string.strOrderPrice, R.string.strOrderStatus, R.string.strExecVol,
			R.string.strExecPrice, R.string.strCancelVol,
			R.string.strEdit, R.string.strCancel, };
	
	private Button btn_Back;
	private Button btn_Buy;
	private Button btn_Sell;
	private Button btn_Home;
	private Button btnAccountSelector;
	
	private LinearLayout layout_Header;
	private LinearLayout layout_Content;
	
	private TextView lbAccount;
	
	private int selectedSubAccountPossition;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.trangthai_lenh);

		InitControlId();
		Load_Current_SubAccount_Info();
		LoadCurrent_SubAccount_OrderStatus();
	}
	
	public void LoadCurrent_SubAccount_OrderStatus() {
		ArrayList<OrderInfo> data = WebService.GetListNewestOrder(Session.currentSubAccount);
		ShowViewStockBalances(data);
	}
	
	private void Load_Current_SubAccount_Info() {
		lbAccount.setText(Session.custAccount);
	}
	
	private void ShowViewStockBalances(ArrayList<OrderInfo> data) {
		try {
			if (data != null && data.size() > 0) {
				layout_Content.removeAllViewsInLayout();
				String text = null;
				int xColor = R.color.whiles;
				for (OrderInfo order : data) 
				{
					TableLayout tableContent = new TableLayout(TrangThaiLenhActivity.this);
					TableRow[] rowContents = new TableRow[StrHeaderId.length];
					TextView[] txtContent = new TextView[StrHeaderId.length];
					for (int i = 0; i < txtContent.length; i++) 
					{
						rowContents[i] = new TableRow(TrangThaiLenhActivity.this);
						
						if(i < 8)
							txtContent[i] = new TextView(TrangThaiLenhActivity.this);
						else
							txtContent[i] = new Button(TrangThaiLenhActivity.this);
						
						xColor = R.color.whiles;
						// set text
						switch (i) {
						case 0:
							text = order.StockSymbol;							
							break;
						case 1:
							text = getResources().getString((order.Side.equals("S"))? R.string.Sell_Title:R.string.Buy_Title);
							xColor = (order.Side.equals("S"))?R.color.down:R.color.up;
							break;
						case 2:
							text = Integer.toString(order.Volume);
							break;
						case 3:
							text = Float.toString(order.Price);
							xColor = Common.SetColorStockInfo(order.Price, order.Ceiling, order.Floor, order.Ref);
							break;
						case 4:
							OrderStatus_Code code = Com.Ring.TradingMobile.Lib.Common.GetOrderStatus_Code(order.OrderStatus);
							switch(code)
							{
								case PROCESS_WAITING:
									text = getResources().getString(R.string.strStatus_Waiting);
									break;
								case MATCH_WAITING:
									text = getResources().getString(R.string.strStatus_Match_Waiting);
									break;
								case ORDER_REJECTED:
									text = getResources().getString(R.string.strStatus_Reject);
									break;
								case ORDER_CANCELLED:
									text = getResources().getString(R.string.strStatus_Cancel);
									break;
								case FULL_MATCHED:
									text = getResources().getString(R.string.strStatus_Matched);
									break;
								default:
									text = "";
									break;
							}
							break;
						case 5:
							text = Integer.toString(order.ExecutedVol);
							break;
						case 6:
							text = Float.toString(order.ExecutedPrice);
							xColor = Common.SetColorStockInfo(order.ExecutedPrice, order.Ceiling, order.Floor, order.Ref);
							break;
						case 7:
							text = Integer.toString(order.CancelledVolume);
							break;
						case 8:
							text = getResources().getString(R.string.strEdit);
							txtContent[i].setEnabled(order.CanUpdate);
							
							//Truyen du lieu id va side cho button sua.
							txtContent[i].setTag(R.id.OrderId, order.OrderId);
							txtContent[i].setTag(R.id.Side, order.Side);
							
							txtContent[i].setOnClickListener(new OnClickListener() {								
								public void onClick(View v) {
									//Lay du lieu duoc truyen trong Tag cua button.									
									String id = v.getTag(R.id.OrderId).toString();
									String side = v.getTag(R.id.Side).toString();
									
									//Khoi tao intent den activity mua/ban.
									Intent intent = new Intent();
									
									if(side.equals("B"))
										intent = new Intent(getBaseContext(), MuaActivity.class);
									else
										intent = new Intent(getBaseContext(), BanActivity.class);
									
									//Truyen du lieu la OrderId.
									Bundle extras = new Bundle();
									extras.putString("OrderId", id);
									
									intent.putExtras(extras);									
									startActivity(intent);
									
									finish();
								}
							});
							
							break;
						case 9:
							text = getResources().getString(R.string.strCancel);
							txtContent[i].setEnabled(order.CanCancel);
							
							//Truyen du lieu id cho button xoa.
							txtContent[i].setTag(R.id.OrderId, order.OrderId);
							
							txtContent[i].setOnClickListener(new OnClickListener() {								
								public void onClick(View v) {
									//Lay du lieu duoc truyen trong Tag cua button.
									final String orderid = v.getTag(R.id.OrderId).toString();									
									
									AlertDialog.Builder builder = new AlertDialog.Builder(TrangThaiLenhActivity.this);
								    builder.setMessage(R.string.strConfirmCancelMessage)
								           .setCancelable(false)
								           .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
								               public void onClick(DialogInterface dialog, int id) {
								            	   Cancel_Order(orderid);
								            	   LoadCurrent_SubAccount_OrderStatus();
								               }
								           })
								           .setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
								               public void onClick(DialogInterface dialog, int id) {
								                    dialog.cancel();
								               }
								           });
								    AlertDialog alert = builder.create();
								    alert.show();								
								}
							});							
							break;
						}
						
						LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
						
						if(i<8)
						{
							txtContent[i].setBackgroundResource(R.drawable.border_color_textview);
							txtContent[i].setGravity(Gravity.RIGHT);
						}
						
						txtContent[i].setText(text);						
						txtContent[i].setTextColor(getResources().getColor(xColor));
						txtContent[i].setHeight(24);
						txtContent[i].setTextSize(12);
						
						txtContent[i].setPadding(0, 0, 2, 0);						
						
						rowContents[i].addView(txtContent[i],layout);
						rowContents[i].setPadding(1, 1, 1, 1);
						tableContent.addView(rowContents[i]);
					}
					
					tableContent.setPadding(0, 10, 0, 10);
					layout_Content.addView(tableContent);
				}
			}
		} catch (Exception ex) {
			Log.d("TAG", ex.toString());
		}
	}

	protected void Cancel_Order(String id) {		
		Log.d("TAG","Canceling order " + id);
		int cancel_order_retcode = WebService.CancelOrder(id, Session.currentSubAccount);
		
		String cancel_msg = "";
		if(cancel_order_retcode !=RET_CODE.SUCCESS.Value)		
			cancel_msg = getResources().getString(R.string.str_order_cancel_not_success);
		else
			cancel_msg = getResources().getString(R.string.str_order_cancel_success);
		
		AlertDialog.Builder builder = new AlertDialog.Builder(TrangThaiLenhActivity.this);
	    builder.setMessage(cancel_msg)
	           .setCancelable(false)
	           .setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	               }
	           });
	    AlertDialog alert = builder.create();
	    alert.show();		
	}

	private void InitControlId() {
		btn_Back = (Button) findViewById(R.id.btnBack);
		btn_Buy = (Button) findViewById(R.id.btn_Mua);
		btn_Sell = (Button) findViewById(R.id.btn_Ban);
		btn_Home = (Button) findViewById(R.id.btnHome);
		btnAccountSelector = (Button) findViewById(R.id.btnAccountSelector);
		layout_Header = (LinearLayout) findViewById(R.id.linearHeader);
		layout_Content = (LinearLayout) findViewById(R.id.linearContent);
		lbAccount = (TextView)findViewById(R.id.lbAccount);

		TableLayout tableHeader = new TableLayout(this);
		TableRow[] rowsHeader = new TableRow[StrHeaderId.length];
		TextView[] txtHeader = new TextView[StrHeaderId.length];
		for (int i = 0; i < txtHeader.length; i++) {
			rowsHeader[i] = new TableRow(this);
			txtHeader[i] = new TextView(this);
			txtHeader[i].setText(StrHeaderId[i]);
			
			if(i<8)
				txtHeader[i].setHeight(24);
			else
				txtHeader[i].setHeight(47);
			
			txtHeader[i].setTextSize(12);
			txtHeader[i]
					.setBackgroundResource(R.drawable.border_color_textview);
			txtHeader[i].setTextColor(getResources().getColor(
					R.color.title_row));
			rowsHeader[i].addView(txtHeader[i]);
			
			rowsHeader[i].setPadding(5, 1, 1, 1);
			tableHeader.addView(rowsHeader[i]);
		}
		tableHeader.setPadding(0, 10, 0, 10);
		layout_Header.addView(tableHeader);
		
		btn_Home.setOnClickListener(new OnClickListener() {
			//@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						TradingMobileLoggedActivity.class);
				startActivity(intent);
				finish();
				onDestroy();
			}
		});
		
		btn_Buy.setOnClickListener(new OnClickListener() {
			//@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						MuaActivity.class);
				startActivity(intent);
				finish();
				onDestroy();
			}
		});
		
		btn_Sell.setOnClickListener(new OnClickListener() {
			//@Override
			public void onClick(View v) {
				Intent intent = new Intent(getBaseContext(),
						BanActivity.class);
				startActivity(intent);
				finish();
				onDestroy();
			}
		});
		
		btn_Back.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				//onDestroy();
			}
		});
		
		btnAccountSelector.setOnClickListener(new OnClickListener(){
			public void onClick(View v){
				AlertDialog.Builder builderSua = new Builder(TrangThaiLenhActivity.this);
				builderSua.setIcon(R.drawable.alert_dialog_icon);
				builderSua.setTitle(R.string.strConfirmSelectSubAccount);

				String[] subAccountList = new String[Session.subCustAccounts.size()];
				for(int i=0; i< subAccountList.length; i++)
					subAccountList[i] = Session.subCustAccounts.get(i);
					
				builderSua.setSingleChoiceItems(subAccountList, Session.currentSubAccountPossition,
						new DialogInterface.OnClickListener() {							
							public void onClick(DialogInterface dialog, int which) {
								selectedSubAccountPossition = which;																
							}
						});
				builderSua.setPositiveButton(R.string.str_ok,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								if(selectedSubAccountPossition == Session.currentSubAccountPossition)
									return;
								
								//Luu lai thong tin subAccount hien tai
								Session.currentSubAccountPossition = selectedSubAccountPossition;
								Session.currentSubAccount = Session.subCustAccounts.get(selectedSubAccountPossition);
								Load_Current_SubAccount_Info();
							}							
						});				
				builderSua.setNegativeButton(R.string.str_cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {								
							}
						});
				builderSua.show();
			}		
		});
	}
	
	@Override
	protected void onResume()
	{
		CheckLogin();
		super.onResume();
	}
	
	private void CheckLogin()
	{
		if(!Session.IsLogin)
		{
			Intent intent = new Intent(getBaseContext(), DangNhapActivity.class);
			startActivity(intent);
			finish();
		}
	}
}